<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #authTree>
        <el-tree
          ref="permTreeRef"
          node-key="value"
          show-checkbox
          :data="menuTree"
          :filter-node-method="handlePermFilter"
          :check-strictly="false"
          class="mt-5"
          @check="
            (checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys) =>
              (formData.menuIds = checkedKeys?.checkedKeys)
          "
        >
          <template #default="{ data }">
            {{ data.label }}
          </template>
        </el-tree>
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import { mockTreeList } from "./data";
import { getDeptList, getOrganizationList } from "@/commonData";
import { phoneRules } from "@/commonData/rules";
import { enableList, roleDataScopeList, roleScopeList } from "@/commonData/dict";
import { useAuth } from "@/views/system/common/hooks/useAuth";
import RoleAPI from "@/api/system/role-api";

const {
  isExpanded,
  permKeywords,
  checkedRole,
  permTreeRef,
  getMenuTreeAndRoleMenu,
  menuTree,

  setRoleMenu,
  handlePermFilter,
  togglePermTree,
  handleAssignPermSubmit,
} = useAuth();

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
  // return { status: "1" };
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const organizationList = ref([]);
const deptList = ref([]);
const roleList = ref([]);

// 部门id改变改变可选角色菜单- 仅仅带出该部门下的权限菜单
const changeAuthMenus = () => {
  nextTick(() => {
    // 还得调用一个靠部门获取权限的接口
    // const deptId = 2;
    // getMenuTreeAndRoleMenu(deptId);
    // console.log(formData.value.deptId, "部门id变化");
  });
};

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  // 1、角色名称-必填
  // 2、角色编码-必填
  // 3、归属机构-必填-下拉
  // 4、归属部门-必填-下拉
  // 5、角色描述
  // 6、角色状态-下拉是否

  // 7、权限设置(读取部门权限接口回显)

  /**
    1、code-角色编码-1
    2、dataScope-数据范围 1:全部 2:部门及子部门 3:本部门 4:本人
    3、deptId-所属部门ID
    4、menus-(最好是menuIds)
    5、name-名称-1
    6、orgNo-所属组织机构编号
    7、remark-备注-1
    8、scope-角色范围 1:全局角色 2:内部角色(部门) 3:销售角色-1
    9、sort-排序
   */

  const list = [
    {
      requiredFlag: true,
      type: "input",
      label: "角色名称",
      prop: "name",
      placeholder: "角色名称",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      requiredFlag: true,
      type: "input",
      label: "角色编码",
      prop: "code",
      placeholder: "角色编码",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      requiredFlag: true,
      type: "tree-select",
      placeholder: "归属机构",
      prop: "orgNo",
      label: "归属机构",
      attrs: {
        filterable: true,
        clearable: true,
        // data: mockTreeList,
        data: organizationList,
        // props: defaultProps,
        "check-strictly": true,
        // "node-key": "id",
        onChange: (val) => {
          getDeptList(deptList, { orgNo: val });
          console.log(val, "机构变化");
        },
      },
    },
    {
      type: "select",
      placeholder: "归属部门",
      label: "归属部门",
      prop: "deptId",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
        onChange: (val) => {
          changeAuthMenus();
        },
      },
      children: deptList,
    },
    {
      type: "select",
      placeholder: "角色状态",
      label: "角色状态",
      prop: "status",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: enableList,
    },
    {
      type: "select",
      placeholder: "角色范围",
      label: "角色范围",
      prop: "scope",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: roleScopeList,
    },
    {
      type: "select",
      placeholder: "数据范围",
      label: "数据范围",
      prop: "dataScope",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: roleDataScopeList,
    },
    {
      type: "input",
      label: "备注",
      prop: "remark",
      placeholder: "备注",
      attrs: {
        autosize: true,
        type: "textarea",
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      slot: "authTree",
      label: "权限设置",
    },
  ];

  addProperty(list);
  return list;
};

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();
  getOrganizationList(organizationList);
  getDeptList(deptList);

  const map: any = {
    create: () => {
      requestFormOptions.value = createRequestFormOptions();
    },
    update: () => {
      requestFormOptions.value = createRequestFormOptions();
    },
  };

  map[type] && map[type]();

  // if (!id) {
  //   getMenuTreeAndRoleMenu();
  // }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await getUser(id);
      changeAuthMenus();
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await RoleAPI.create(data);
      // ElMessage.success("操作成功");
    } else if (formType.value === "update") {
      await RoleAPI.update(data.id, data);
      // ElMessage.success("操作成功");
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const mockList = [
  { label: "模拟数据1", value: 1 },
  { label: "模拟数据2", value: 2 },
  { label: "模拟数据3", value: 3 },
  { label: "模拟数据4", value: 4 },
  { label: "模拟数据5", value: 5 },
];

const getFormData = () => {
  return formData.value;
};
</script>
